// 用户端图库API调用脚本
class UserGalleryAPI {
    constructor() {
        this.baseURL = '/api'; // 后端API基础URL
        this.cache = new Map();
        this.cacheTTL = 300000; // 5分钟缓存
    }

    // 获取启用的轮播图
    async getActiveCarouselImages() {
        const cacheKey = 'active-carousel';
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const response = await fetch(`${this.baseURL}/carousel/active`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            if (data.success) {
                this.setCachedData(cacheKey, data.data);
                return data.data;
            } else {
                console.warn('获取轮播图失败，使用默认图片');
                return this.getDefaultCarouselImages();
            }
        } catch (error) {
            console.error('获取轮播图失败:', error);
            return this.getDefaultCarouselImages();
        }
    }

    // 获取当前Logo
    async getCurrentLogo() {
        const cacheKey = 'current-logo';
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const response = await fetch(`${this.baseURL}/logos/current`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            if (data.success) {
                this.setCachedData(cacheKey, data.data);
                return data.data;
            } else {
                console.warn('获取Logo失败，使用默认Logo');
                return this.getDefaultLogo();
            }
        } catch (error) {
            console.error('获取Logo失败:', error);
            return this.getDefaultLogo();
        }
    }

    // 获取产品图片
    async getProductImages(productId) {
        const cacheKey = `product-images-${productId}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const response = await fetch(`${this.baseURL}/product-images/product/${productId}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            if (data.success) {
                this.setCachedData(cacheKey, data.data);
                return data.data;
            } else {
                return [];
            }
        } catch (error) {
            console.error('获取产品图片失败:', error);
            return [];
        }
    }

    // 获取博客封面图
    async getBlogCoverImage(blogId) {
        const cacheKey = `blog-cover-${blogId}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const response = await fetch(`${this.baseURL}/blog-images/blog/${blogId}/cover`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            if (data.success) {
                this.setCachedData(cacheKey, data.data);
                return data.data;
            } else {
                return null;
            }
        } catch (error) {
            console.error('获取博客封面图失败:', error);
            return null;
        }
    }

    // 缓存管理
    getCachedData(key) {
        const cached = this.cache.get(key);
        if (cached && Date.now() - cached.timestamp < this.cacheTTL) {
            return cached.data;
        }
        return null;
    }

    setCachedData(key, data) {
        this.cache.set(key, {
            data: data,
            timestamp: Date.now()
        });
    }

    // 默认轮播图数据（API不可用时使用）
    getDefaultCarouselImages() {
        return [
            {
                id: 1,
                name: '轮播图1',
                imageUrl: '/static/tp/2a8ff2dc-e9ef-426d-b1e8-a0fe7470a1a2.jpg',
                title: '品质骑行，全球直达',
                description: '严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧。',
                link: '/products',
                buttonText: '查看产品'
            },
            {
                id: 2,
                name: '轮播图2',
                imageUrl: '/static/tp/6b3cd5f7-f8d7-4c54-babe-5a0b74450e4a.jpg',
                title: 'ubike',
                description: '我们是ubike，就想让你买到省心的骑行装备！',
                link: '/about',
                buttonText: '了解我们'
            },
            {
                id: 3,
                name: '轮播图3',
                imageUrl: '/static/tp/43ab696e-5269-44c4-aa9e-1900812219b3.jpg',
                title: '专业服务团队',
                description: '专业团队，为您提供最优质的服务',
                link: '/contact',
                buttonText: '联系我们'
            }
        ];
    }

    // 默认Logo数据
    getDefaultLogo() {
        return {
            id: 1,
            name: '主Logo',
            imageUrl: '/static/tp/Logo.png',
            alt: 'ubike'
        };
    }
}

// 创建全局实例
window.userGalleryAPI = new UserGalleryAPI();